package com.study.zouchao.superproject.mypublishtask;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.MyBaseFragment;
import com.study.zouchao.superproject.comtasklist.fragment.ITaskListContract;
import com.study.zouchao.superproject.comtasklist.fragment.presenter.TaskListPresenter;
import com.study.zouchao.superproject.main.view.MainActivity;
import com.study.zouchao.superproject.mypublishtask.adapter.ChooseUserAdapter;
import com.study.zouchao.superproject.mypublishtask.model.entity.MyPublishTaskListResult;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.EventBusEvent;
import com.study.zouchao.superproject.util.EventBusEvent_C;
import com.study.zouchao.superproject.util.EventBusUtils;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;
import com.study.zouchao.superproject.util.ui.EmptyRecyclerView;
import com.study.zouchao.superproject.util.ui.OnSlideSeeMoreLisenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by Administrator on 2017/6/23.
 */

public class MyPublishTaskFragment extends MyBaseFragment implements IPublishTaskListContract.IPublishTaskListView,  SwipeRefreshLayout.OnRefreshListener,  OnSlideSeeMoreLisenter.IOnSlideToBottomListener {

    @BindView(R.id.id_rv_mypublishtask)
    EmptyRecyclerView mRvTask;
    @BindView(R.id.id_refreshing_task_list)
    SwipeRefreshLayout mRefreshing;

    @BindView(R.id.id_rl_empty_view)
    RelativeLayout mRlEmptyView;

    private View mSeeMoreloading;
    private IPublishTaskListContract.IPublishTaskListPresenter mPresenter;

    private static final String KEY_PARAM1 = "KEY_PARAM1";

    private AlertDialog mAlertDialog;

    @Override
    protected View getLoadingTargetView() {
        return getCurrentFragmentRootView();
    }

    @Override
    protected int getFragmentLayoutID() {
        return R.layout.fragment_publish_task;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBusUtils.register(this);
        mPresenter = new MyPublishPresenter(getActivity(), this);
        Log.d("replace>>>", "list");

        init();
    }
    private void init() {
        mRvTask.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        mRvTask.setEmptyView(
                mRlEmptyView,
                false, true
        );
        mPresenter.initRecyclerView(mRvTask);
        mRefreshing.setOnRefreshListener(this);
        mRvTask.addOnScrollListener(new OnSlideSeeMoreLisenter(this));

    }

    @Override
    public void onRefresh() {
        mPresenter.onRefreshingData();
    }

    @Override
    public void showRefreshingLoading(boolean isShow) {
        if (mRefreshing != null)    mRefreshing.setRefreshing(isShow);

    }

    @Override
    public void showSeeMoreLoading(boolean isShow) {
        if (mSeeMoreloading != null) mSeeMoreloading.setVisibility(isShow ? View.VISIBLE : View.INVISIBLE);

    }

    @Override
    public void showSnackBar(String title) {
        if (mRvTask == null)    return;
        ToastUtils.showSnackbar(mRvTask, title, Snackbar.LENGTH_SHORT);

    }

    private MyPublishTaskListResult.TaskItemBean.EnrolledListBean mSelectedEnroll = null;

    private TextView mTvSelectedNickName = null;


    private String getStatusError(int intNowStatus) {
        String status;
        switch (intNowStatus) {
            case 2 :
                status = "当前任务已经执行...";
                break;
            case 3 :
                status = "当前任务已经过期...";
                break;
            case 4 :
                status = "当前任务已经完成...";
                break;
            default:
                status = "当前任务状态有误 ...";
                break;
        }
        return status;
    }


    @Override
    public void showChooseDialog(View v, final int taskId, List<MyPublishTaskListResult.TaskItemBean.EnrolledListBean> enrolledList, int taskStatus) {
        if (taskStatus >= 2) {
            showSnackBar("注："+getStatusError(taskStatus));
            return;
        }
        //TODO: 假如已经选择了某人(tastStatis=2)、则不可弹出框
        if (enrolledList.size() == 0)    {
            ToastUtils.showShort(App.getAppContext(), "尚未有人报名");
            return;
        }
        dismissAlertDialog();
        View viewChooseUser = LayoutInflater.from(getActivity()).inflate(R.layout.layout_choose_user, null, false);
        final RecyclerView rvChooseUser = (RecyclerView) viewChooseUser.findViewById(R.id.id_rv_chooseUser);
        mTvSelectedNickName = (TextView) viewChooseUser.findViewById(R.id.id_tv_selected);
        rvChooseUser.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        ChooseUserAdapter adapter = new ChooseUserAdapter(getActivity(), enrolledList);
        rvChooseUser.setAdapter(adapter);
        adapter.setOnItemClickListener(new ChooseUserAdapter.IRvItemClickListener() {
            @Override
            public void onItemClick(View v, MyPublishTaskListResult.TaskItemBean.EnrolledListBean item) {
                mSelectedEnroll = item;
                if (mTvSelectedNickName!=null && mSelectedEnroll.getNickName()!=null) {
                    mTvSelectedNickName.setText(("已选择："+mSelectedEnroll.getNickName()));
                }
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setView(viewChooseUser)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mSelectedEnroll!=null && !StringUtils.isEmpty(mSelectedEnroll.getUserName()))
                            showSnackBar("选择:"+mSelectedEnroll.getNickName());
                        else showSnackBar("尚未选择");
                        if (mPresenter!=null && mSelectedEnroll!=null
                                    &&!StringUtils.isEmpty(mSelectedEnroll.getUserName())) {
                            mPresenter.chooseUser(mSelectedEnroll.getUserName(), taskId);
                        }
                        dismissAlertDialog();
                    }
                })
                .setCancelable(true);
        mAlertDialog = builder.show();
    }

    @Override
    public void setSeeMoreLoading(View footerLoadingView) {
        mSeeMoreloading = footerLoadingView;
    }

    private void dismissAlertDialog() {
        if (mAlertDialog!=null && mAlertDialog.isShowing()) mAlertDialog.dismiss();
    }

    @Override
    public void onSeeMore() {
        mPresenter.loadSeeMore();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBusEvent event) {
        switch (event.getTag()) {
            case EventBusEvent_C.EVENT_REFRESH_MY_PUBLISH_TASK_LIST :
                onRefresh();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissAlertDialog();
        if (mPresenter != null) mPresenter.onDestroyPresente();
        EventBusUtils.unRegister(this);
    }
}
